<?php

namespace Home\Controller;

use Think\Controller;
use Common\Controller\HomeController;

class CheckController extends HomeController {
    
    public function __construct() {
        parent::__construct();
        $this->member_id = session('member_id');//会员ID
        if (empty($this->member_id)) {
            redirect(U('Register/login') . '?ret=' . urlencode(__SELF__));
        }
    }
    
    //完善订购信息
    public function index() {
        //获得已选购物商品信息
        $CartObj = new \Home\Model\CartModel();
        $id = I('get.id','');
        $total_weight = 0;
        $cart_list = $CartObj->get_cart($id); 
        foreach($cart_list as $k => $v) {
            $cart_list[$k]['total'] = tofixed($v['price'] * $v['num'],2);
            $total_weight += $v['weight'];
        }
        $this->id = $id;//已选商品
        $this->cart_list = $cart_list;
        $this->total_weight = $total_weight;
        //获取默认收货地址
        $MemberAddress = new \Home\Model\MemberAddressModel();
        $address_default = $MemberAddress->get_default_address($this->member_id);
        if(!empty($address_default)) {
            $this->address_default_id = $address_default['id'];
        }
        
        //获取配送方式
        $ConfigDeliveryObj = new \Home\Model\ConfigDeliveryModel();
        $delivery = $ConfigDeliveryObj->get_list();
        $this->delivery = $delivery;
        
        //会员余额
       // 
       // $member_money = $MemberObj->get_money($this->member_id);
       // $this->member_money = $member_money;
        //会员积分
        $MemberObj = new \Home\Model\MemberModel();
        $member_point = $MemberObj->get_point($this->member_id);
        $this->member_point = $member_point;

        //购物车总金额
        $cart_total = $CartObj->get_total($id);
        $level_id = $MemberObj->show_member_level($this->member_id);
        $MemberLevel = new \Home\Model\MemberLevelModel();
        $discount = $MemberLevel->get_level_discount($level_id);
        $this->cart_total = $cart_total*$discount/100;
        
        //可使用优惠券
        $MemberYhqObj = new \Home\Model\MemberYhqModel();
        $this->youhuiquan = $MemberYhqObj->can_use_now_one($this->member_id,$cart_total);
		//print_r($this->youhuiquan);
        $this->seo=array('seo_title'=>'订单结算','seo_keywords'=>'订单结算','seo_description'=>'订单结算');
        $this->display();
    }
    
    //提交订单数据
    public function checkout() {
        $MemberObj = new \Home\Model\MemberModel();
        $data['status'] = 'success';
        $sel_address_id = I('post.sel_address_id',0);
        $sel_delivery_id = I('post.sel_delivery_id',0);
        $delivery_time = I('post.delivery_time','');
        $pay_type = I('post.pay_type','1');
		$payment = I('post.payment','支付宝');
        $total_pay_money = I('post.total_pay_money',0);
        $total_point = I('post.total_point',0);
        $remark_member = I('post.remark_member','');
        $yhq_ids = I('post.yhq_ids','');
        if($sel_address_id == 0) {
            $data['status'] = 'error';
            $data['msg'] = "请选择或者填写收货地址！";
        } elseif($sel_delivery_id == 0) {
            $data['status'] = 'error';
            $data['msg'] = "请选择配送方式！";
        } elseif($delivery_time == "") {
            $data['status'] = 'error';
            $data['msg'] = "请选择配送时间！";
        } else {
            $order['time_create'] = time();//下单时间
            $order['order_type'] = 0;//订单类型 0：普通订单
            $order['member_id'] = $this->member_id;//会员ID
            $OrderObj = new \Fwadmin\Model\OrderModel();
            $order['order_no'] = $OrderObj->get_order_no($order['order_type'], $order['member_id']);//订单编号
            $order['remark_member'] = $remark_member;
            //状态
            $order['status'] = 1;//订单状态： 1未审核 2已审核 3已完成 4已取消 5已作废
            $order['status_pay'] = 1;//支付状态： 1未支付 2部分支付 3已支付
            $order['status_delivery'] = 1;//配送状态：1未发货 2已发货 3已部分发货 4已收货
            $order['pay_type'] = $pay_type;
			$order['payment'] = $payment;
            //购物车商品信息
            $CartObj = new \Home\Model\CartModel();
            $id = I('post.id','');
            $total_weight = 0;
            $cart_list = $CartObj->get_cart($id); 
            foreach($cart_list as $k => $v) {
                $cart_list[$k]['total'] = tofixed($v['price'] * $v['num'],2);
                $total_weight += $v['weight'];
            }
            if(empty($cart_list)) {
                $data['status'] = 'error';
                $data['msg'] = "请选择购物车商品！";
                $this->ajaxReturn($data);
               exit();
            }
            //购物车总金额
            $order['total_cart'] = $CartObj->get_total($id);
            $order['total_weight'] = $total_weight;//总重量
        
            //获得收获地址
            $MemberAddress = new \Home\Model\MemberAddressModel();
            $address = $MemberAddress->get_address($this->member_id, $sel_address_id);
            if(empty($address)) {
                $data['status'] = 'error';
                $data['msg'] = "请选择或者填写收货地址！";
                $this->ajaxReturn($data);
                exit();
            }
            $order['addr_realname'] = $address['realname'];
            $order['addr_country'] = $address['country'];
            $order['addr_province'] = $address['province'];
            $order['addr_city'] = $address['city'];
            $order['addr_area'] = $address['area'];
            $order['addr_address'] = $address['address'];
            $order['addr_zip'] = $address['zip'];
            $order['addr_tel'] = $address['tel'];
            $order['addr_phone'] = $address['phone'];
            $order['addr_email'] = $address['email'];
            //配送方式
            $ConfigDeliveryObj = new \Home\Model\ConfigDeliveryModel();
            $delivery = $ConfigDeliveryObj->find($sel_delivery_id);
            if(empty($delivery)) {
                $data['status'] = 'error';
                $data['msg'] = "请选择配送方式！";
                $this->ajaxReturn($data);
                exit();
            }
            if ($delivery['type'] == 3) {//商品自提
                $order['takeself'] = '';
            }
            $order['delivery_type'] = $delivery['delivery_name'];//配送方式
            $order['delivery_time'] = $delivery_time;//配送时间
            $total_delivery = $ConfigDeliveryObj->count_total_delivery($sel_delivery_id, $total_weight,$sel_address_id);//运费
            $order['total_delivery'] = $total_delivery;
            $order['total_save_price'] = 0;
            $order['total'] = $order['total_cart'] + $order['total_delivery'] + $order['total_save_price'];
            $order['total_discount'] = 0;
            $order['total_pay'] = 0;
            //积分抵扣
            $member_point = $MemberObj->get_point($this->member_id);
            if($total_point > $member_point) {
                $data['status'] = 'error';
                $data['msg'] = "你的积分不足！";
                $this->ajaxReturn($data);
                exit();
            }
            
            $point_1_to_money = $this->config['point_1_to_money'];
            $point_pay_percent = $this->config['point_pay_percent'];
            $total_pay_point = $total_point * $point_1_to_money;
            if($total_pay_point > $order['total']*$point_pay_percent*100) {
                $data['status'] = 'error';
                $data['msg'] = "积分支付金额超过比例限制！";
                $this->ajaxReturn($data);
                exit();
            }
            $order['total_point'] = $total_point;
            $order['total_pay_point'] = $total_pay_point;
            
            //优惠券
            $MemberYhqObj = new \Home\Model\MemberYhqModel();
            $total_pay_yhq = 0;
            if($yhq_ids != "") {
                $total_pay_yhq = $MemberYhqObj->total_money($yhq_ids, $this->member_id);
            }
            $order['total_pay_yhq'] = $total_pay_yhq;
            $order['yhq_ids'] = $yhq_ids;
            
            //是否保价
            $order['is_save_price'] = 0;
            $order['get_point'] = 0;//获得赠送积分
            //发票
            $order['is_invoice'] = 0;//是否需要发票：0不索要 1索要
            $order['invoice_title'] = '';//发票抬头

            $order['source'] = 1;//'订单来源：PC'
            //保存订单操作
            $order_id = $OrderObj->data($order)->add();
            if($order_id > 0) {
                //添加订单商品表
                foreach($cart_list as $k => $v) {
                    $cart['order_id'] = $order_id;
                    $cart['order_no'] = $order['order_no'];
                    $cart['member_id'] = $order['member_id'];
                    $cart['goods_id'] = $v['goods_id'];
                    $cart['goods_sn'] = $v['goods_sn'];
                    $cart['goods_item_id'] = $v['item_id'];
                    $cart['goods_num'] = $v['num'];
                    $cart['goods_name'] = $v['goods_name'];
                    $cart['goods_price'] =$v['price'];
                    $cart['goods_picture'] = $v['picture'];
                    $cart['goods_weight'] = $v['weight'];
                    $cart['goods_spec'] = $v['spec_array'];
                    $cart['is_comment'] = 0;
                    $OrderGoodsObj = M('OrderGoods');
                    $cart_flag = $OrderGoodsObj->data($cart)->add();
                    if($cart_flag <= 0) {
                        $SystemErrorObj = new \Fwadmin\Model\SystemErrorModel();
                        $SystemErrorObj->add_error('checkout', '订单商品添加失败', $OrderGoodsObj->_sql());
                    }
                }
                //添加订单记录
                $OrderObj->add_order_record($order_id, '你提交了订单');
                //余额支付金额
                if($total_pay_money > 0) {
                    $member_money = $MemberObj->get_money($this->member_id);
                    if($member_money >= $total_pay_money) {
                        $MemberMoneyObj = new \Fwadmin\Model\MemberMoneyModel();
                        $MemberMoneyObj->add_record($this->member_id,-$total_pay_money, '余额支付', 0);
                        $OrderObj->pay_3($order_id, '余额支付', $total_pay_money);
                    }
                }
                //积分支付扣除会员金额
                if($total_point > 0) {
                    $MemberPointObj = new \Fwadmin\Model\MemberPointModel();
                    $MemberPointObj->add_record($this->member_id,-$total_point, '积分抵扣', 0);
                }
                
                //使用优惠券
                if($yhq_ids != "" && $total_pay_yhq>0) {
                    $MemberYhqObj->use_ids($yhq_ids, $this->member_id,$order_id);
                }
                
                //如果待支付金额为0 自动更新支付状态
                $OrderObj->update_pay_status($order_id);
                        
                //删除购物车商品
                if($id != '') {
                   $arr_id = explode('-',$id);
                   $CartObj->del_sel($arr_id);
                } else {
                    $CartObj->clear();
                }
                $data['order_id'] = $order_id;
            } else {
                $data['status'] = 'error';
                $data['msg'] = "订单提交出错！";
            }
            $this->ajaxReturn($data);
        }
    }
    
    /**
     * 订单提交成功页面
     * @param int $id 订单ID
     */
    public function success($id) {
        $OrderObj = new \Fwadmin\Model\OrderModel();
        $order = $OrderObj->find($id);
        
        //防止查看别人的订单
        if($order['member_id'] !== $this->member_id) {
            echo '非法操作';
            exit();
        }
        $order['pay_type_str'] = $OrderObj->get_pay_type($order['pay_type']);//支付方式
        $order['status_str'] = $OrderObj->show_status_member($order['status'], $order['status_pay'], $order['status_delivery'],$order['pay_type']);//订单状态
        $order['total_show'] = $order['total'] - $order['total_discount'];//显示价格
        $order['total_need_pay'] = $OrderObj->get_total_need_pay($order);//待支付金额
        $order['total_need_pay'] = round($order['total_need_pay'],2);
   
        $this->order = $order;
        
        //订单跟踪信息
        $this->record = $OrderObj->get_record($id);
        //订单购物车信息
        $this->goods = $OrderObj->get_goods($id);
        $this->display();
    }
    
    /**
     * 订单提支付页面
     * @param int $id 订单ID
     */
    public function pay($id) {
        $OrderObj = new \Fwadmin\Model\OrderModel();
        $order = $OrderObj->where(array('member_id'=>$this->member_id,'order_id'=>$id))->find();
        if(empty($order)) {
            echo '非法操作！';
            exit();
        }
        $order['total_need_pay'] = $OrderObj->get_total_need_pay($order);
        $this->order = $order;
        
        //支付方式
        $PaymentObj = new \Home\Model\ConfigPaymentModel();
        $this->payment = $PaymentObj->get_list();
        
        //会员可用余额
        $MemberObj = new \Home\Model\MemberModel();
        $this->menber_money = $MemberObj->get_money($this->member_id);
        
        $this->display();
    }
    
    /**
     * 余额支付
     * @param int $order_id 订单ID
     */
    public function pay_yue($order_id) {
        $OrderObj = new \Fwadmin\Model\OrderModel();
        $MemberObj = new \Home\Model\MemberModel();
        $order = $OrderObj->field('total,total_discount,total_pay,total_pay_point,status_pay,total_pay_yhq')->where(array('member_id'=>$this->member_id,'order_id'=>$order_id))->find();
        if(empty($order)) {
            echo '非法操作！';
            exit();
        }
        if($order['status_pay'] == 3) {
            echo '你的订单已支付';
            exit();
        }
        $total_pay_money = $OrderObj->get_total_need_pay($order);//待支付金额
        $member_money = $MemberObj->get_money($this->member_id);//会员余额
        if($member_money >= $total_pay_money) {
            $MemberMoneyObj = new \Fwadmin\Model\MemberMoneyModel();
            $flag = $MemberMoneyObj->add_record($this->member_id,-$total_pay_money, '余额支付', 0);//余额减少
            if($flag > 0) {
                $OrderObj->pay_3($order_id, '余额支付', $total_pay_money);//更新订单状态
                echo 'success';
            }
        } else {
            echo '你的余额不足！请先充值';
        }
    }
    
    /**
     * 计算运费
     * @param type $delivery_id 配送方式ID
     * @param type $weight 重量（单位克）
     * @param type $address_id 地址ID
     */
    public function count_delivery($delivery_id,$weight,$address_id) {
        $ConfigDeliveryObj = new \Home\Model\ConfigDeliveryModel();
        $total_delivery = $ConfigDeliveryObj->count_total_delivery($delivery_id, $weight,$address_id);
        if($total_delivery >= 0) {
            $data['status'] = 'success';
            $data['total_delivery'] = $total_delivery;
        } else {
            $data['status'] = $total_delivery;
            $data['total_delivery'] = -9999;
        }
        $this->ajaxReturn($data);
    }
    
    //获取会员收货地址
    public function get_address() {
        layout(false);
        //会员收货地址信息
        $MemberAddress = new \Home\Model\MemberAddressModel();
        $address = $MemberAddress->search($this->member_id);
        $address_list = $address['list'];
        $this->address_list = $address_list;
		//print_r($address_list);
        $this->display();
    }

}